<template>
  <div class="search-result">
    <!-- .sync，错误处理的监听，为了解决实时监听 -->
    <van-list
      v-model="loading"
      :finished="finished"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      finished-text="没有更多了"
      @load="onLoad"
    >
      <van-cell
        v-for="(article,i) in list"
        :key="i"
        :title="article.title"
        :to="'/article/' + article.art_id"
      />
    </van-list>
  </div>
</template>

<script>
import { getSearchResult } from '@/api/search'
export default {
  name: 'SearchResult',
  components: {},
  props: {
    searchText: {
      type: String,
      require: true
    }
  },
  data () {
    return {
      list: [],
      loading: false, // 本次加载进行
      finished: false, // 加载状态
      page: 1,
      perPage: 20,
      error: false // 加载失败显示与否
    }
  },
  computed: {},
  watch: {},
  created () { },
  mounted () { },
  methods: {
    async onLoad () {
      // 请求获取数据
      try {
        const { data } = await getSearchResult({
          page: this.page, // 页码
          per_page: this.perPsge, // 每页大小
          q: this.searchText// 查询关键字
        })
        // 2.把数据追加给数组
        const { results } = data.data
        this.list.push(...results)
        // 3.关闭本次请求
        this.loading = false
        // 判断是否还有数据
        if (results.length) {
          this.page++// 获取下页数据
        } else {
          this.finished = true // 没有数据了，将加载状态设置结束
        }
      } catch (err) {
        // 展示加载失败的提示状态
        this.error = true
        // 加载失败了 loading 也要关闭
        this.loading = false
      }
    }
  }
}
</script>

<style scoped lang="less"></style>
